
function getQueryString(name) {
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    let r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return r[2];
    };
    return 0;
}


var checkItervalId = setInterval(()=>{
    if(!header_quickView){
        clickButton();
    }

    checkPopSuccess();
},2000)


var no_pop_time = 0 ;
var all_check_times = 0;
function checkPopSuccess(){
    all_check_times = 0;
    if(header_can_user===true){
        console.log("check header_can_user",header_can_user);
        return;
    }

    const high_closeBox = document.querySelector('.captcha_click_close_box');
    if (high_closeBox) {
        console.log("high_closeBox",high_closeBox);
        block();
    }

    const closeBox = document.querySelector('.captcha_canvas_close_box');
    //已经确定有滑动窗口
    if (!closeBox) {
        console.log("checkPopSuccess","no closeBox");
    }

    //已经计算好了滑动窗口需要移动多少
    if(closeBox && sm_left_px_move > 0){
        console.log("sm_left_px_move",sm_left_px_move);
        if(start_move===false){
            simulateSlider(sm_left_px_move);
        }
    }

    const goods_btn = document.querySelector('.goods-btn__add');
    console.log("set goods_btn",goods_btn);
    if(goods_btn){
        header_can_user = true;
        console.log("set header_can_user",header_can_user);
    }

    if(!closeBox && !goods_btn){
        no_pop_time++;
        console.log("no_pop_time",no_pop_time);
        if(no_pop_time > 10){
            page_reload();
        }
    }
    if(all_check_times > 500){
        page_reload();
    }
}

var start_move = false;

var reRryTime = 0;



function clickButton(){

    const closeBox = document.querySelector('.captcha_canvas_close_box');
    if (closeBox) {
        return
    }

    var button = document.querySelector('.product-card__add-btn.price-wrapper__addbag-btn');
    simulateClick(button);

}

var sm_left_px_move = 0;
var api1_fail_number = 0;
var api2_fail_number = 0;
var api3_fail_number = 0;
var api4_fail_number = 0;
var success_time = 0;

var header_quickView = "";
var header_header_static_v2 = "";
var header_header_realtime = "";
var useLocalHeader_realtime = false;
var useLocalHeader_quickview = false;
var last_fail_api_index = 0 ;
var run_index = 0;
var sm_eror = false;
var run_number = 0;
var check_pop_success = true;
var header_can_user = false;
chrome.runtime.onMessage.addListener(async (msg, sender) => {

    console.log(msg);
    console.log(header_can_user,api3_fail_number,api4_fail_number,api2_fail_number);

    if(msg.type==='header_quickView'){
        header_quickView = msg.headers;
    }else if(msg.type==='header_static_v2'){
        header_header_static_v2 = msg.headers;
    }else if(msg.type==='header_realtime'){
        header_header_realtime = msg.headers;
    }else if(msg.type==='sm_pic'){
        findLargestTransparentAreaByUrl(msg.pic).then(leftMostX => {
            if(leftMostX > 0){
                sm_left_px_move = leftMostX;
            }
            console.log('Left Most X:', leftMostX);
        })
        .catch(error => {
            console.error('Error:', error);
            page_reload();
        });
    }else if(msg.data.goods_id && header_can_user && header_quickView && (api3_fail_number<=1 || api4_fail_number<=1 ||api2_fail_number <=1)){
        run_number++;
        console.log(run_number,api3_fail_number);
        if(run_number<=2 && api3_fail_number===1){
            page_reload();
            return;
        }
        let reload = false;
        if(run_number>5){
            reload = true;
        }
        console.log("reload",reload);
        if(api3_fail_number <= 1 && run_number <= 2){
            getDataByApiStaticV2(msg,reload);
        }else if(api2_fail_number <=1 && run_number <= 4){
            get_goods_detail_realtime_data(msg,reload);
        }else if(api4_fail_number <=1 && run_number <= 5){
            getDataByQuickView(msg,reload);
        }else if(run_number <= 6 && api3_fail_number <= 1){
            getDataByApiStaticV2(msg,reload);
        }else {
            page_reload();
        }
    }/*else if(api1_fail_number <=2){
        getDataByApiByProductRealTime(msg);
    }else {
        block();
    }*/
})

function block(){
    console.log("sheinblock_yuenanstock");
    fail_number = 0;
    var type = "sheinblock_yuenanstock";

    let block_time = getQueryString("block");
    let block_time_int= parseInt(block_time, 10);
    if(block_time_int <=0){
        block_time_int = 180;
    }
    console.log("block_time_int",block_time_int);
    chrome.runtime.sendMessage({ data: {type ,block_time_int}, close: false });
    let this_lock_time = (block_time_int -5) * 1000;

    clearInterval(checkItervalId);
    console.log("this_lock_time",this_lock_time);
    setTimeout(() => {
        location.reload()
    },this_lock_time);
}

function getDataByQuickView(msg,reload){
    console.log("start api 4")
    const url = 'https://s1.shein.com/api/productInfo/quickView/get?_ver=1.1.8&_lang=en&goods_id='+msg.data.goods_id+'&mallCode=1&lockmall=0&isQuick=1&bid=my'; // 替换为您的接口地址

    let requestHeader= getHeaderByType("quickview");

    console.log(requestHeader);
    fetch(url, {
        method: 'GET',
        headers: requestHeader,
        credentials: 'include' // 如果需要携带 cookie
    })
        .then(response => {
            if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
            return response.json();
        })
        .then(data => {
            console.log(data);
            if(data['code']==='836100'){
                api4_fail_number++;
                sm_eror= true;
                page_reload();
                //clickButton();
                last_fail_api_index = 4;
                console.log("api4_fail_number:"+api4_fail_number);
            }else{
                api4_fail_number = 0;
                getStockByQuickView(data,msg.data.id,msg);
            }

            if(reload===true){
                page_reload();
            }

        })
        .catch(error => {
            if(reload===true){
                page_reload();
            }
            api4_fail_number ++;
            last_fail_api_index = 4;
            console.log("api4_fail_number:"+api4_fail_number);
            console.log(error)
        });

}
function getDataByApiByProductRealTime(msg){
    console.log("start api 1");
    var goods_id = msg.data.goods_id;
    const url = 'https://s1.shein.com/api/productInfo/realTimeData/query?_ver=1.1.8&_lang=en'; // 替换为您的接口地址
    const payload = {
        goods_id: msg.data.goods_id,
        mallCode: "1",
        tsp: {},
        specialSceneType: 0,
        tags: [
            { tagId: "2422", tagValueId: ["9680"] },
            { tagId: "2423", tagValueId: ["83281"] },
            { tagId: "3199", tagValueId: ["502"] },
            { tagId: "3864", tagValueId: ["12.72"] },
            { tagId: "3865", tagValueId: ["12.64"] },
            { tagId: "3866", tagValueId: ["12.64"] },
            { tagId: "4015", tagValueId: ["12.74"] },
            { tagId: "4016", tagValueId: ["12.74"] },
            { tagId: "4017", tagValueId: ["12.74"] },
            { tagId: "4018", tagValueId: ["2"] },
            { tagId: "4448", tagValueId: ["67"] },
            { tagId: "4607", tagValueId: ["2388"] },
            { tagId: "60007749", tagValueId: ["1"] },
            { tagId: "100000112", tagValueId: [1] },
            { tagId: "100000317", tagValueId: [1] },
            { tagId: "100000444", tagValueId: [1] },
            { tagId: "100000445", tagValueId: [1] },
            { tagId: "600015000", tagValueId: ["1"] },
            { tagId: "600029050", tagValueId: ["1"] },
            { tagId: "600137885", tagValueId: ["1"] }
        ],
        transportTypes: ["urgent_express"]
    };

    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload)
    })
        .then(response => {
            if (!response.ok) {
                api1_fail_number++;
                console.log("api1_fail_number:"+api1_fail_number);
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            return response.json();

        })
        .then(data => {
            api1_fail_number = 0;
            var jsonObject  = data;
            var sku_list = jsonObject['data']['productInfo']['attrSizeList']['sale_attr_list'][goods_id]['sku_list'];
            console.log(sku_list);

            var stock_map = {};
            var index = 0;
            var price = jsonObject['data']['productInfo']['getPrice']['salePrice']['amount'];
            sku_list.forEach((item) => {
                if(item['sku_sale_attr'] && item['sku_sale_attr'].length>0){
                    stock_map[item['sku_sale_attr'][0]['attr_value_name']] = item['stock'];
                }else{
                    stock_map[index] = item['stock'];
                }
                index++;

            })

            var type = "sheinstock_s1";
            var id = msg.data.id;
            console.log(id);
            console.log(stock_map);
            console.log(price);
            chrome.runtime.sendMessage({ data: {type,id, stock_map,price}, close: false });


        })
        .catch(error => {
            console.error('Error:', error);
            api1_fail_number++;
            console.log("api1_fail_number:"+api1_fail_number);
        });
}


function getHeaderByType(type){
    console.log("getHeaderByType",type);
    if(sm_eror===true){
        let requestHeader ={
            'accept': 'application/json, text/plain, */*',
            'accept-language': 'zh-CN,zh;q=0.9',
            'anti-in': '0_1.9.1_c38d61_-qx5b0yIhYmNyQg4_nzJw02_XsG7Wbct9SKxL8BesDsAtw5l6XjE4uY2weB9dAatfxMSTdlKbd01lOIVfhNNpdD137c835Lx4N4DCfMSfp66DcYAsPXeyIXkj6hz0reu9PPJ-i9Ry-ZcN2QH_fSWLo5hd5uQECpV0q-zBPYRkrx2LUddIH1SEyjz9DNwu173w-XOcJ0sVk_ubuqPT4t3HK7g-8SiJodsQcItiljQVsOCayA9OoYE14OarnEA2HZXsIqKvxi7aidKvdwY7KteHbcLfxjF2_GwfxFfTY9csb6o0b6HX9MvXvcP05Ho2pepxfZ3XTeqw4PYkyHkKqVDxqBwg1xSJKlEOKyXD3SkCaGcVNrmEfP8_6VioIYou7MCZ0TcH6iVDiN5q2AbhJ1XshURP7yOqnZLmjdf8G2l_XfOQ3SHgIIQlG9JFYKoNkZ2MjKdquUeEpPjJ5pR_aH1QrYgeHv9z3AWK2jbjQ4bsfbO0uM_4ZK_iI_qGhaC_QRrOa9RCu_aG2ilaoiDocXnrKv5jUamfWt-IySkyjAikHFo0rybUKZehMiIhoRoTWfeJSE62J0vRjR76_TgrG1XerIZyAG6HNa-Ny1wi_3ZRqsA4RrM5WWmYIrH_MfsI2q1waNo1JJZO9EiXgKFd3kCQJseDQFFf-7CR8uJDYYd7C9i0iGwk8gOyXmswakoO2qKQD_ZaLia0mfiHOd4kXSAfJqNNyqG_vTjeSEXNmZRwN4cGoln1A8FkBEKsMUc6uY7m',
            'armortoken': 'T0_3.3.0_HrzEkoY1JjaE3mp_fOTINtzBb-h-EkHI0vvSoOmZuZcgwjbqAfmTkQm-fjEVe-gXeN9a2jl02nli0HXVAdgRVvXqDIfiPnUWKtA5HvEwH3RAxPc4sBDMcXOJpkm0tW_mqFiuAGw6zghfuIDcFn_Vuyd5REj4JUH6F8gsPL3qzJjakISTWpoJfszsJHKxxwy7_1747379001280',
            'priority': 'u=1, i',
            'referer': 'https://s1.shein.com/',
            'sec-ch-ua': '"Google Chrome";v="135", "Not-A.Brand";v="8", "Chromium";v="135"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"macOS"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36',
            // Add other needed headers from the second request here as necessary
        }
        console.log("not have header");
        return requestHeader;
    }
    if(type === 'static_v2' && header_header_static_v2){
        let requestHeader = {};
        header_header_static_v2.forEach(header => {
            requestHeader[header.name]=header.value;
        });
        console.log("have header");
        return requestHeader;

    }else if(type === 'realtime' && header_header_realtime){
        let requestHeader = {};
        header_header_realtime.forEach(header => {
            requestHeader[header.name]=header.value;
        });
        console.log("have header");
        return requestHeader;

    }else if(type === 'quickview' && header_quickView){
        let requestHeader = {};
        header_quickView.forEach(header => {
            requestHeader[header.name]=header.value;
        });
        console.log("have header");
        return requestHeader;
    }else{
        return null;
    }

}

var useLocalHeader = false;
function getDataByApiStaticV2(msg,reload){
    console.log("start api 3");
    var url = "https://s1.shein.com/bff-api/product/get_goods_detail_static_data_v2?_ver=1.1.8&_lang=en&goods_id="+msg.data.goods_id+"&mall_code=1&isUserSelectedMallCode=0&isHideEstimatePriceInfo=0&specialSceneType=0&bid=my";


    let requestHeader = getHeaderByType("static_v2")

    fetch(url, {
        method: 'GET',
        headers: requestHeader,
        credentials: 'include' // 如果需要携带 cookie
    })
        .then(response => {
            if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
            return response.json();
        })
        .then(data => {
            if(data['code']==='836100'){
                sm_eror= true;
                //clickButton();
                page_reload();
                api3_fail_number ++;
                last_fail_api_index = 3;
                console.log("api3_fail_number:"+api3_fail_number);
            }else{
                api3_fail_number = 0;
                doWitdhDataJob(data,msg.data.id,msg);
            }
            if(reload===true){
                page_reload();
            }

        })
        .catch(error => {
            if(reload===true){
                page_reload();
            }
            api3_fail_number ++;
            last_fail_api_index = 3;
            console.log("api3_fail_number:"+api3_fail_number);
            console.log(error)
        });
}

function get_goods_detail_realtime_data(msg,reload){
    console.log("start api 2");
    var url = "https://s1.shein.com/bff-api/product/get_goods_detail_realtime_data?_ver=1.1.8&_lang=en&goods_id=" + msg.data.goods_id + "&mallCode=1&isUserSelectedMallCode=0&isQueryIsPaidMember=1&isQueryCanTrail=0&isHideEstimatePriceInfo=0&specialSceneType=0&countryId=226&bid=my";

    let requestHeader = getHeaderByType("realtime")

    fetch(url, {
        method: 'GET',
        headers: requestHeader,
        credentials: 'include' // 如果需要携带 cookie
    })
        .then(response => {
            if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
            return response.json();
        })
        .then(data => {
            if(data['code']==='836100'){
                api2_fail_number++;
                last_fail_api_index = 2;
                console.log("api2_fail_number:"+api2_fail_number);
                sm_eror= true;
                page_reload();
                //clickButton();
            }else{
                api2_fail_number = 0;
                doWitdhDataJob(data,msg.data.id,msg);
            }
            if(reload===true){
                page_reload();
            }

        })
        .catch(error => {
            if(reload===true){
                page_reload();
            }
            api2_fail_number ++;
            last_fail_api_index = 2;
            console.log("api2_fail_number:"+api2_fail_number);
            console.log(error);
     });
}




/*





// content.js
(function() {
    const open = XMLHttpRequest.prototype.open;
    const send = XMLHttpRequest.prototype.send;

    XMLHttpRequest.prototype.open = function(method, url) {
        this._url = url; // Save the URL
        return open.apply(this, arguments);
    };

    XMLHttpRequest.prototype.send = function() {
        this.addEventListener('load', function() {
            if (this._url && this._url.includes('s1.shein.com')) {
                console.log('Intercepted response:', this.responseText);
            }
        });
        return send.apply(this, arguments);
    };
})();


// content.js
(function() {
    const originalFetch = window.fetch;

    window.fetch = function(...args) {
        return originalFetch.apply(this, args).then(response => {
            const clonedResponse = response.clone(); // Clone the response for consumption
            const url = args[0];

            // Check if the URL matches
            if (typeof url === 'string' && url.includes('s1.shein.com')) {
                clonedResponse.text().then(body => {
                    console.log('Intercepted fetch response body:', body);
                });
            }

            return response; // Return original response for normal handling
        });
    };
})();


// content.js
const targetNode = document.body;
const config = { childList: true, subtree: true };

const callback = (mutationsList) => {
    for (let mutation of mutationsList) {
        if (mutation.type === 'childList') {
            const nodes = mutation.addedNodes;
            nodes.forEach(node => {
                if (node.nodeType === Node.ELEMENT_NODE && node.tagName === 'SCRIPT') {
                    console.log("New script added: ", node.src);
                    // 可以在这里检查是否有新的 fetch 或 XHR 请求
                }
            });
        }
    }
};

const observer = new MutationObserver(callback);
observer.observe(targetNode, config);*/